﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 多播委托
{
    class Program
    {
        static void Main(string[] args)
        {
            //int i = 0;
            //i -= --i;
            //Console.WriteLine(i);
            //Console.ReadKey();


            //、、多播委托
            Console.WriteLine("//多播委托");
            ProgressReporter p = WriteProgressToConsole;
            p += WriteProgressToFile;

            Utility.Match(p);
            Console.WriteLine("Done.");
            Console.ReadKey();

            //静态方法和实例方法对于委托的区别
            Console.WriteLine("//静态方法和实例方法对于委托的区别");
            X x = new X();
            p = x.InstanceProgress;
            p += X.staInstanceProgress;
            p(1);
            Console.WriteLine(p.Target == x); // True
            Console.WriteLine(p.Method); // Void InstanceProgress(Int32)
            Console.ReadKey();

            //泛型委托
            int[] values = { 1, 34, 56, 100};
            Utility.Calculator(values,Double);
            string[] strvalues = { "123", "456", "789" };
            Utility.Calculator(strvalues, pStr);
            Console.ReadKey();
        }

        static void WriteProgressToConsole(int p)
        {
            Console.WriteLine(p + "%");
        }
        static void WriteProgressToFile(int p)
        {
            System.IO.File.AppendAllText("text.txt", p + "%");

        }

        //泛型委托
        static int Double(int x) { return x * 2; }
        static string pStr(string x) { return x.PadLeft(6, '0'); }
    }
    public delegate void ProgressReporter(int percentComplete);
    //泛型委托
    public delegate  T Calculator<T> (T tag);
    public class Utility
    {
        public static void Match(ProgressReporter p)
        {
            if (p != null)
            {
                for (int i = 0; i < 10; i++)
                {
                    p(i * 10);
                    System.Threading.Thread.Sleep(1000); //每秒
                }
            }
        }
        //泛型委托
        public static void Calculator<T>(T[] values,Calculator<T> c)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = c(values[i]);
                Console.WriteLine(values[i]);
                System.Threading.Thread.Sleep(100);
            }

        }
    }
    /// <summary>
    /// 静态方法和实例方法对于委托的区别
    /// </summary>
    public class X
    {
        public void InstanceProgress(int percentComplete)
        {
            Console.WriteLine("我是实例方法");
            // do something
        }
        public static void staInstanceProgress(int percentComplete)
        {
            Console.WriteLine("我是静态方法");
            //做点什么。。。
        }
    }
}
